package instrument;

import org.example.Manager;
import org.example.Reception;
import org.example.User;
import product.Movie;
import product.SaleRecord;
import product.Seat;
import product.Show;

import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class FileUtil {
    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    // 保存用户列表到文件
    public static void saveUsers(List<User> users, String filePath) {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))) {
            for (User user : users) {
                // 格式: id,username,password,usertype,telephone,registerTime,needChangePassword
                String line = String.join(",",
                        String.valueOf(user.getId()),
                        user.getUserName(),
                        user.getPassword(),
                        user.getUserType(),
                        user.getUserTelephone(),
                        sdf.format(user.getRegisterTime()),
                        String.valueOf(user.isNeedChangePassword()));
                writer.write(line);
                writer.newLine();
            }
        } catch (IOException e) {
            System.out.println("保存用户信息失败: " + e.getMessage());
        }
    }

    // 从文件加载用户列表
    public static List<User> loadUsers(String filePath) {
        List<User> users = new ArrayList<>();
        File file = new File(filePath);

        if (!file.exists()) {
            return users;
        }

        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = reader.readLine()) != null) {
                String[] parts = line.split(",");
                if (parts.length != 7) {
                    continue; // 格式错误，跳过
                }

                try {
                    int id = Integer.parseInt(parts[0]);
                    String username = parts[1];
                    String password = parts[2];
                    String userType = parts[3];
                    String telephone = parts[4];
                    Date registerTime = sdf.parse(parts[5]);
                    boolean needChangePassword = Boolean.parseBoolean(parts[6]);

                    User user;
                    if ("经理".equals(userType)) {
                        user = new Manager(id, username, password, telephone, registerTime, needChangePassword);
                    } else if ("前台".equals(userType)) {
                        user = new Reception(id, username, password, telephone, registerTime, needChangePassword);
                    } else { // 管理员
                        user = new User(id, username, password, userType, telephone, registerTime, needChangePassword);
                    }

                    users.add(user);
                } catch (NumberFormatException | ParseException e) {
                    System.out.println("解析用户信息失败: " + e.getMessage());
                }
            }
        } catch (IOException e) {
            System.out.println("加载用户信息失败: " + e.getMessage());
        }

        return users;
    }

    // 保存电影列表到文件
    public static void saveMovies(List<Movie> movies, String filePath) {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))) {
            for (Movie movie : movies) {
                // 格式: name,director,actors,intro,duration,score,isShowing
                String line = String.join(",",
                        movie.getName(),
                        movie.getDirector(),
                        movie.getActors(),
                        movie.getIntro(),
                        String.valueOf(movie.getDuration()),
                        String.valueOf(movie.getScore()),
                        String.valueOf(movie.isShowing()));
                writer.write(line);
                writer.newLine();
            }
        } catch (IOException e) {
            System.out.println("保存电影信息失败: " + e.getMessage());
        }
    }

    // 从文件加载电影列表
    public static List<Movie> loadMovies(String filePath) {
        List<Movie> movies = new ArrayList<>();
        File file = new File(filePath);

        if (!file.exists()) {
            return movies;
        }

        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = reader.readLine()) != null) {
                String[] parts = line.split(",");
                if (parts.length != 7) {
                    continue;
                }

                try {
                    String name = parts[0];
                    String director = parts[1];
                    String actors = parts[2];
                    String intro = parts[3];
                    int duration = Integer.parseInt(parts[4]);
                    double score = Double.parseDouble(parts[5]);
                    boolean isShowing = Boolean.parseBoolean(parts[6]);

                    movies.add(new Movie(name, director, actors, intro, duration, score, isShowing));
                } catch (NumberFormatException e) {
                    System.out.println("解析电影信息失败: " + e.getMessage());
                }
            }
        } catch (IOException e) {
            System.out.println("加载电影信息失败: " + e.getMessage());
        }

        return movies;
    }

    // 保存场次信息到文件
    public static void saveShows(List<Show> shows, String filePath) {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))) {
            for (Show show : shows) {
                // 格式: id,movieName,hall,time,price,rowCount,colCount,seats
                String line = String.join("|",
                        String.valueOf(show.getId()),
                        show.getMovie().getName(),
                        show.getHall(),
                        sdf.format(show.getTime()),
                        String.valueOf(show.getPrice()),
                        String.valueOf(show.getRowCount()),
                        String.valueOf(show.getColCount()),
                        show.seatsToString()
                );
                writer.write(line);
                writer.newLine();
            }
        } catch (IOException e) {
            System.out.println("保存场次信息失败: " + e.getMessage());
        }
    }

    // 从文件加载场次信息
    public static List<Show> loadShows(String filePath, List<Movie> movies) {
        List<Show> shows = new ArrayList<>();
        File file = new File(filePath);

        if (!file.exists()) {
            return shows;
        }

        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = reader.readLine()) != null) {
                String[] parts = line.split("\\|");
                if (parts.length != 8) {
                    continue;
                }

                try {
                    int id = Integer.parseInt(parts[0]);
                    String movieName = parts[1];
                    String hall = parts[2];
                    Date time = sdf.parse(parts[3]);
                    double price = Double.parseDouble(parts[4]);
                    int rowCount = Integer.parseInt(parts[5]);
                    int colCount = Integer.parseInt(parts[6]);
                    String seatsStr = parts[7];

                    // 查找对应的电影
                    Movie movie = null;
                    for (Movie m : movies) {
                        if (m.getName().equals(movieName)) {
                            movie = m;
                            break;
                        }
                    }

                    if (movie == null) {
                        continue; // 电影不存在，跳过
                    }

                    Show show = new Show(id, movie, hall, time, price, rowCount, colCount);
                    show.stringToSeats(seatsStr); // 恢复座位信息
                    shows.add(show);
                } catch (NumberFormatException | ParseException e) {
                    System.out.println("解析场次信息失败: " + e.getMessage());
                }
            }
        } catch (IOException e) {
            System.out.println("加载场次信息失败: " + e.getMessage());
        }

        return shows;
    }

    // 保存售票记录到文件
    public static void saveSaleRecords(List<SaleRecord> records, String filePath) {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))) {
            for (SaleRecord record : records) {
                // 格式: 票号|场次ID|座位行|座位列|价格|销售时间|是否退票|退票时间|退票金额
                String refundTime = record.getRefundTime() != null ? sdf.format(record.getRefundTime()) : "";
                String line = String.join("|",
                        record.getTicketId(),
                        String.valueOf(record.getShow().getId()),
                        String.valueOf(record.getSeat().getRow()),
                        String.valueOf(record.getSeat().getCol()),
                        String.valueOf(record.getPrice()),
                        sdf.format(record.getSaleTime()),
                        String.valueOf(record.isRefunded()),
                        refundTime,
                        String.valueOf(record.getRefundAmount())
                );
                writer.write(line);
                writer.newLine();
            }
        } catch (IOException e) {
            System.out.println("保存售票记录失败: " + e.getMessage());
        }
    }

    // 从文件加载售票记录
    public static List<SaleRecord> loadSaleRecords(String saleRecordFilePath, List<Show> shows) {
        List<SaleRecord> saleRecords = new ArrayList<>();
        File file = new File(saleRecordFilePath);

        if (!file.exists()) {
            return saleRecords;
        }

        try (BufferedReader reader = new BufferedReader(new FileReader(saleRecordFilePath))) {
            String line;
            while ((line = reader.readLine()) != null) {
                String[] parts = line.split("\\|");
                if (parts.length != 9) { // 修正为9个字段
                    continue;
                }

                try {
                    String ticketId = parts[0];
                    int showId = Integer.parseInt(parts[1]);
                    int seatRow = Integer.parseInt(parts[2]);
                    int seatCol = Integer.parseInt(parts[3]);
                    double price = Double.parseDouble(parts[4]);
                    Date saleTime = sdf.parse(parts[5]);
                    boolean isRefunded = Boolean.parseBoolean(parts[6]);
                    Date refundTime = parts[7].isEmpty() ? null : sdf.parse(parts[7]);
                    double refundAmount = Double.parseDouble(parts[8]);

                    // 查找对应的场次
                    Show show = null;
                    for (Show s : shows) {
                        if (s.getId() == showId) {
                            show = s;
                            break;
                        }
                    }

                    if (show == null) {
                        continue; // 场次不存在，跳过
                    }

                    Seat seat = new Seat(seatRow, seatCol);
                    SaleRecord record = new SaleRecord(ticketId, show, seat, price, saleTime);
                    record.setRefunded(isRefunded);
                    record.setRefundTime(refundTime);
                    record.setRefundAmount(refundAmount);
                    saleRecords.add(record);
                } catch (NumberFormatException | ParseException e) {
                    System.out.println("解析售票记录失败: " + e.getMessage());
                }
            }
        } catch (IOException e) {
            System.out.println("加载售票记录失败: " + e.getMessage());
        }

        return saleRecords;
    }
}